<template>
  <el-dialog :visible.sync="currentVisible"
             append-to-body
             destroy-on-close
             :close-on-click-modal="false"
             :title="$t('custom.dataset.linkedbtn')"
             custom-class="linked-widgets-dialog"
             width="1000px">
    <el-form v-loading="loading"
             class="flex flex-col"
             style="height:500px">
      <el-checkbox v-if="$hasPermission('sys:dataset:link:widget:show:all')"
                   v-model="form.checked"
                   style="margin-bottom: 10px;">Show All Widget</el-checkbox>

      <BGrid :columns="columns"
             :allowResizing="true"
             :allowFiltering="true"
             :showColumnMenu="true"
             :allowGrouping="true"
             :allowReordering="true"
             :allowTextWrap="true"
             :allowSorting="true"
             :allowPaging="true"
             :showColumnChooser="true"
             :sortSettings="{
             columns: [
            { field: 'name', direction: 'Ascending' }
          ]
           }"
             :filterSettings="{ type: 'Excel' }"
             :toolbar="['Search', 'ColumnChooser']"
             :dataSource="linkedWidgets"
             class="h-0"
             ref="b-grid" />
    </el-form>

    <template slot="footer">
      <el-button size="small"
                 @click="onCancel">{{ $t('cancel') }}</el-button>
    </template>

    <Model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="closeQueryModel"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :mappingForm="mappingFormSetting"
           :updateGadget="upgradeGadgetSetting" />
  </el-dialog>
</template>

<script>
import { get } from 'lodash'
import BGrid from '@/components/storybook/b-grid'
import { renderLinkedWidgetColumns } from './index.schema'
import bus from '@/components/storybook/utilties/bus'
import { deleteLinkedWidget, fetchLinkedWidgets } from '@/api/new'

export default {
  name: 'BLinkedWidgets',
  components: {
    BGrid,
    Model: () => import('@/components/gadget/query-model/query-model.vue')
  },
  props: {
    visible: Boolean,
    dataSourceId: String
  },
  data () {
    return {
      form: {
        checked: false
      },
      loading: false,
      linkedWidgets: [],


      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: '',
          gadgetId: '',
          gadgetType: '',
          gadgetSetting: {},
          reuse: true
        }
      },
    }
  },

  computed: {
    currentVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    columns () {
      return renderLinkedWidgetColumns()
    }
  },
  watch: {
    async 'form.reuse' () {
      try {
        this.loading = true
        await this.getLinkedWidgets()
      } finally {
        this.loading = false
      }
    }
  },
  beforeCreate () {
    bus.$on('event:view-linked-widget', (data) => {
      this.onView(data)
    })
    bus.$on('event:delete-linked-widget', (data) => {
      this.onDelete(data)
    })
  },
  created () {
    this.init()
  },
  destroyed () {
    bus.$off('event:view-linked-widget')
    bus.$off('event:delete-linked-widget')
  },
  methods: {
    async onView (data) {
      this.queryModelDefaultSetting.dataInfo.businessId = data.businessId
      this.queryModelDefaultSetting.dataInfo.id = data.id
      this.queryModelDefaultSetting.dataInfo.businessType = data.businessType
      this.queryModelDefaultSetting.dataInfo.gadgetId = data.gadgetId
      this.queryModelDefaultSetting.dataInfo.gadgetType = data.gadgetType
      this.queryModelDefaultSetting.dataInfo.gadgetSetting = data.gadgetSetting
      this.$store.state.isWidget = true
      this.queryModelDefaultSetting.showSetting = true
    },
    async onDelete (data) {
      try {
        this.loading = true

        let params = {
          sysModelId: data.id,
          reportId: data.reportId,
          dashboardId: data.dashboardId
        }

        const { data: response } = await deleteLinkedWidget(params)
        if (response.code !== 0) {
          throw response.msg
        }
        this.$message.success(response.msg)
        this.init()
      } catch (error) {
        this.loading = false
        this.$message.error(error)
      } finally {
      }
    },
    async init () {
      try {
        this.loading = true
        const [linkedWidgets] = await Promise.all([this.getLinkedWidgets()])

        this.linkedWidgets = linkedWidgets
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    async getLinkedWidgets () {
      const { checked, ...rest } = this.form
      let params = {
        ...rest,
        sysDatasetId: this.dataSourceId
      }

      if (!checked) {
        params.reuse = true
      }


      const { data: response } = await fetchLinkedWidgets(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return get(response, 'data.sysModels') || []
    },
    onCancel () {
      this.currentVisible = false
    },

    upgradeGadgetSetting () { },
    mappingFormSetting (to, from) { },
    async closeQueryModel () {
      this.queryModelDefaultSetting.showSetting = false
    }
  }
}
</script>
